class AdminUser < ActiveRecord::Base
  validates_presence_of :user_name
  validates_uniqueness_of :user_name
  
  #before_validation :check_password
  
  #attr_accessible :user_name
  
  STATUSES = { 0 => '默认', -1 => '冻结', -2 => '删除' }
  
  named_scope :valid, :conditions => { :status => 0 }
  
  named_scope :filter, lambda { |params|
    c, h = [], {}
    
    unless params[:id].blank?
      c << "id LIKE :id"
      h[:id] = "%#{params[:id]}%"
    end
    unless params[:user_name].blank?
      c << "user_name LIKE :user_name"
      h[:user_name] = "%#{params[:user_name]}%"
    end
    unless params[:email].blank?
      c << "email LIKE :email"
      h[:email] = "%#{params[:email]}%"
    end
    
    { :conditions => [c.join(' AND '), h] }
  }
  
  class << self
  
    def authenticate(user_name, password)
      user = find_by_user_name(user_name)
      if user and user.crypted_password != encrypted_password(password, user.salt)
        user = nil
      end
      user
    end
    
  end
  
  def to_s
    user_name
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.crypted_password = self.class.encrypted_password(self.password, self.salt)
  end
  
  def del
    update_attributes!(:status => -1)
  end
  
  private
  
    def self.encrypted_password(pwd, salt)
      Digest::SHA1.hexdigest("#{pwd}lwk-kqy-lz#{salt}")
    end

    def create_new_salt
      self.salt = Digest::SHA1.hexdigest(Time.now.to_s + rand.to_s)
    end
    
    #TODO delete admin has bug
#    def validate
#      errors.add_to_base('密码不能为空!') if self.password.blank?
#    end
end
